package xin.yangshuai.juc01.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Question1
 *
 * @author shuai
 * @date 2022/3/14
 */
public class Question1 {

    ArrayBlockingQueue<String> queue;

    public Question1(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    /**
     * 抛出异常
     */
    public void addAndRemove() {

        System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));
        System.out.println(queue.add("c"));
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());

    }

    /**
     * 特殊值
     */
    public void offerAndPoll() {
        System.out.println(queue.offer("a"));
        System.out.println(queue.offer("b"));
        System.out.println(queue.offer("c"));
        System.out.println(queue.offer("d"));
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }

    /**
     * 阻塞
     */
    public void putAndTake() throws InterruptedException {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    System.out.println(Thread.currentThread().getName() + queue.take());

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        queue.put("a");
        queue.put("b");
        queue.put("c");
        queue.put("d");
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    queue.put("e");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        System.out.println(queue.take());
    }

    /**
     * 超时
     */
    public void offerAndPoll2() {
    }
}

class Result1 {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
        Question1 question1 = new Question1(queue);
        question1.putAndTake();

    }
}
